const jwt = require('jsonwebtoken')

const errorTypes = require('../constants/error_types')
const service = require('../service/user.service')
const { md5Password } = require('../utils/password_handle')
const { PUBLIC_KEY } = require('../app/config')
const { checkMoment } = require('../service/auth.service')

const verifyLogin = async (ctx, next) => {
  console.log('验证用户账号密码是否正确middleware')
  // 1.获取用户名密码
  const { name, password } = ctx.request.body
  //   2.校验用户名或者密码不能为空
  if (!name || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }
  //   3.校验用户是否存在
  const userIsExists = await service.getUserByname(name)
  const user = userIsExists[0]
  if (!user) {
    const error = new Error(errorTypes.USER_NOT_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  //   4.校验密码是否正确(加密后的密码)
  if (md5Password(password) !== user.password) {
    const error = new Error(errorTypes.USERNAME_OR_PASSWORD__WRONG)
    return ctx.app.emit('error', error, ctx)
  }
  //   5.通过
  ctx.user = user
  await next()
}
const verifyAuth = async (ctx, next) => {
  console.log('验证用户是否token合法middleware')
  try {
    // 1.获取token
    const authorization = ctx.headers.authorization
    const token = authorization.replace('Bearer ', '')
    // 2.使用公钥对密码进行验证
    const results = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256'],
    })
    ctx.user = results
    console.log(`${results.name}已登陆`)
    await next()
  } catch (err) {
    const error = new Error(errorTypes.UNAUTHORIZATION)
    ctx.app.emit('error', error, ctx)
  }
}
const verifyPermission = async (ctx, next) => {
  console.log('验证用户权限middleware')
  // 1.获取对应数据
  const { momentId } = ctx.params
  const { content } = ctx.request.body
  const { id, name } = ctx.user
  // 2.查询是否具备对应权限
  const results = await checkMoment(momentId, id)
  if (!results) {
    const error = new Error(errorTypes.NO_PERMISSION)
    ctx.app.emit('error', error, ctx)
  } else {
    await next()
  }
}
module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission,
}
